<template>
  <div class="dragbox">
    <el-divider content-position="center">物料存储明细信息</el-divider>
    <el-table :data="tableDatas" border style="width: 100%" row-key="id" @selection-change="handleSelectionChange">
      <el-table-column prop="materialName" label="存储库位" width="700" fixed>
        <template #default="scope">
          <el-button type="primary" class="button" @click="emit('selectSeat', scope.row.warehouseSeat.id)">选择</el-button>
          <!--仓库级联选择组件-->
          <WmsWarehouseCascadeSelectComponent
            ref="wmsWarehouseCascadeSelectFormComponentRef"
            v-model:warehouseSeatId="scope.row.warehouseSeat.id"
            :disabled="true"
          />
        </template>
      </el-table-column>
      <el-table-column prop="materialModel" label="物料名" width="200">
        <template #default="scope">
          <el-input v-model="scope.row.materialInventory.material.model" disabled />
        </template>
      </el-table-column>
      <el-table-column prop="materialModel" label="批次" width="200">
        <template #default="scope">
          <el-input v-model="scope.row.materialBatch.batchNumber" disabled />
        </template>
      </el-table-column>
      <el-table-column prop="materialModel" label="库存" width="200">
        <template #default="scope">
          <el-input v-model="scope.row.inventory" disabled />
        </template>
      </el-table-column>
      <!-- <el-table-column prop="quantity" label="数量" width="180">
        <template #default="scope">
          <el-form-item label-width="0" :prop="'carTechnologyDetails.' + scope.$index + '.quantity'" :rules="detailRule.quantity">
            <el-input v-model.number="scope.row.quantity" placeholder="请输入物料数量" />
          </el-form-item>
        </template>
      </el-table-column> -->
    </el-table>
    <!--物料选择对话框-->
    <MaterialSelectDialogComponent ref="materialSelectDialog" @afterSubmit="afterMaterialSelect" />
  </div>
</template>

<script setup lang="ts">
//导入拖拽插件
// import draggable from 'vuedraggable';
import MaterialSelectDialogComponent from '@/components/mes/MaterialSelectDialogComponent.vue';
import WmsWarehouseCascadeSelectComponent from '@/components/wms/WmsWarehouseCascadeSelectComponent.vue';
import Sortable from 'sortablejs';
import urls from '@/api/request/urls';
import type { CarTechnologyDetail, Material } from '@/types/interface/mes_interface';
import { nextTick, onMounted, ref } from 'vue';
import Request from '@/api/request/request';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { WmsMaterialInventoryDetail } from '@/types/interface/wms_interface';
const emit = defineEmits(['selectSeat']);
//工艺明细模块===============================================================
//接收父组件表单的工艺详情列表
const tableDatas = defineModel<WmsMaterialInventoryDetail[]>({
  required: false,
  default: []
});
//工艺明细的表单验证规则
const detailRule = {
  materialId: [{ required: true, message: '不能为空', trigger: 'change' }],
  quantity: [
    { required: true, message: '不能为空', trigger: 'blur' },
    { type: 'number', message: '必须为数字值' }
  ]
};
//全选按钮动作
const multipleSelection = ref<WmsMaterialInventoryDetail[]>([]); // 复选框选择的记录row
const handleSelectionChange = (selection: WmsMaterialInventoryDetail[]) => {
  // 当选择项发生变化时会触发该事件，这里用于获取选择的记录（多选）.value可以获取所有选择了的行记录row
  multipleSelection.value = selection;
};
//删除多个详情
const deletes = async (): Promise<void> => {
  if (multipleSelection.value.length > 0) {
    ElMessageBox.confirm(`确定要删除这${multipleSelection.value.length}个记录吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        //遍历复选框选中的集合
        for (let carTechnologyDetailSelect of multipleSelection.value) {
          //删除被选中的元素
          // tables.value = tables.value.filter((item) => item.sort !== carTechnologyDetailSelect.sort);
          //等待DOM删除完成，必须要加。
          await nextTick();
        }
        //清空选中元素
        multipleSelection.value.length == 0;
      })
      .catch(() => {
        // 点击了取消按钮
      });
  } else {
    ElMessage.error('请至少选择一条数据');
  }
};
//物料列表
const materials = ref<Material[]>([]);
const getMaterials = async (name: string) => {
  const resData: any = await new Request(urls.API_URL_BACKSTAGE_MES_MATERIAL + '/all', null, { params: { name: name } }).get();
  if (resData.success) {
    return resData.data;
  }
};
onMounted(async () => {
  materials.value = await getMaterials('');
});
//添加新的表单记录
const add = () => {
  //获取最后一个元素的排序
  let sort = 1; //默认从0开始
  if (tableDatas.value.length > 0) {
    //获取最后一个元素的值
    const carTechnologyDetailLast: CarTechnologyDetail = tableDatas.value[tableDatas.value.length - 1];
    sort = carTechnologyDetailLast.sort! + 1;
  }
  let carTechnologyDetailNew: CarTechnologyDetail = {
    id: sort.toString(),
    sort: sort,
    material: {
      name: ''
    }
  };
  tableDatas.value.push(carTechnologyDetailNew);
};
//远程获取物料列表
// const materialSelectloading = ref(false); //物料下拉框加载状态
// const remoteGetMaterials = async (query: string) => {
//   if (query) {
//     materialSelectloading.value = true;
//     materials.value = await getMaterials('');
//     materialSelectloading.value = false;
//   } else {
//     materials.value = [];
//   }
// };
//物料选择对话框
const materialSelectDialog = ref();
let carTechnologyDetailOfCurrent: CarTechnologyDetail | null = null; //用于记录当前选择的工艺详情
const selectMaterial = async (carTechnologyDetail: CarTechnologyDetail) => {
  carTechnologyDetailOfCurrent = carTechnologyDetail;
  //打开物料选择对话框
  await materialSelectDialog.value.openDialog();
};
//获取在物料选择框选择的物料
const afterMaterialSelect = (materials: Material[]) => {
  //将当前选择的物料赋给相应的工艺详情
  carTechnologyDetailOfCurrent!.materialId = materials[0].id;
  carTechnologyDetailOfCurrent!.material = materials[0];
};
</script>

<style scoped></style>
